﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace CRM.Extensions
{
    public static class EnumExtension
    {
        public static string GetDescription(this Enum @enum, string @default = "")
        {
            var enumType = @enum.GetType();
            var value = int.Parse(Enum.Format(enumType, Enum.Parse(enumType, @enum.ToString()), "d"));
            var fieldInfo = enumType.GetField(Enum.GetName(enumType, value)!);
            if (fieldInfo!.GetCustomAttribute(typeof(DescriptionAttribute), false) is DescriptionAttribute descriptionAttribute)
            {
                return descriptionAttribute.Description;
            }
            return  !string.IsNullOrEmpty(@default) ? @default : @enum.ToString();
        }
    }
}